package mysql

import (
	"strings"

	"github.com/jinzhu/gorm"
	"gorm.io/gorm/clause"

	//"gorm.io/gorm/clause"
	"time"
	"web_app/models"
	//"github.com/jinzhu/gorm"
	//"gorm.io/gorm"
	//"gorm.io/gorm/clause"
)

func CreatePost(post *models.Post) (err error) {
	p := models.Post{
		PostId:      post.PostId,
		AuthorId:    post.AuthorId,
		CommunityId: post.CommunityId,
		Content:     post.Content,
		Title:       post.Title,
		CreatedAt:   time.Now(),
		UpdatedAt:   time.Now(),
	}
	err = db.Table("post").Create(&p).Error
	return
}

//func GetPostById(id uint64) (postDetail *models.PostDetail, err error) {
//	postDetail = new(models.PostDetail)
//	err = db.Table("post").
//		Select([]string{"post.post_id", "post.title", "post.content",
//			"users.username", "community.community_name", "post.created_at", "post.updated_at"}).
//		Where("post_id = ?", id).
//		Joins("left join community ON community.community_id = post.community_id").
//		Joins("left join users ON users.user_id = post.author_id").
//		Find(postDetail).Error
//	if gorm.IsRecordNotFoundError(err) {
//		err = ErrorInvalidId
//	}
//	return
//}

func GetPostlById(id uint64) (post *models.Post, err error) {
	post = new(models.Post)
	err = db.Table("post").
		Select([]string{"post_id", "title", "content", "author_id",
			"community_id", "created_at", "updated_at"}).
		Where("post_id = ? ", id).Find(post).Error
	//fmt.Printf("%v\n", post)
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorInvalidId
	}
	return
}

func GetPostList(pagination *models.Pagination) (posts []*models.Post, err error) {
	var count int64
	err = db.Table("post").Count(&count).Error
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorInvalidId
		return
	}
	posts = make([]*models.Post, 0, count)
	offset := (pagination.Page - 1) * pagination.Limit
	err = db.Table("post").Order(pagination.Sort).Offset(int(offset)).Limit(int(pagination.Limit)).
		Select([]string{"post_id", "title", "content",
			"author_id", "community_id", "created_at", "updated_at"}).Find(&posts).Error
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorInvalidId
	}
	return
}

func GetPostListByIdList(idList []string) (posts []*models.Post, err error) {

	posts = make([]*models.Post, 0, len(idList))

	err = db.Table("post").Select([]string{"post_id", "title", "content",
		"author_id", "community_id", "created_at", "updated_at"}).
		Clauses(clause.OrderBy{
			Expression: clause.Expr{
				SQL:                "FIND_IN_SET(post_id,?)",
				Vars:               []interface{}{strings.Join(idList, ",")},
				WithoutParentheses: true,
			}}).
		Where("post_id in (?)", idList).
		Find(&posts).Error
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorInvalidId
	}
	return
}
